#import "Core.h"

// 지향 흘러가게 보여줘야됨!


@implementation NineDayNavigationController

- (id)initWithRootViewController:(PrayViewController *)rootViewController
{
	if ( (self = [super init]) != nil ) {
		_rootViewController = rootViewController;
		self.title = @"9일기도";
		_nineDayViewController = [[NineDayViewController alloc] initWithRootViewController:_rootViewController];
		self.viewControllers = [NSArray arrayWithObjects:_nineDayViewController, nil];
		self.navigationBar.tintColor = [UIColor colorWithRed:87.0f/255.0f green:77.0f/255.0f blue:78.0f/255.0f alpha:1.0f];
	}
	
	return self;
}

- (void)onSettingChanged:(PraySettingData *)data
{
	[_nineDayViewController onSettingChanged:data];
}

- (void)dealloc
{
	[_nineDayViewController release];
	
	[super dealloc];
}

@end


@interface NineDayViewController (private)

- (void)initSubView:(NSString*)purpose;
- (void)editPressed;
- (void)historyPressed;
- (void)showMystery:(NSInteger)rosaryIndex;
- (void)hideMystery;
- (void)onMysteryHideComplete;
- (void)mysteryViewPressed;
- (void)scrollPurposeView;
- (void)updatePurposeView;
@end

@implementation NineDayViewController (private)

- (void)editPressed
{
	EditPurposeViewController*	editPurposeView;
	
	editPurposeView = [[EditPurposeViewController alloc] initWithPurpose:_purpose rootViewController:_rootViewController filename:@"nineDayPurposeHistory.inf"];	
	editPurposeView.delegate = self;
	
	[self.navigationController pushViewController:editPurposeView animated:YES];
	[editPurposeView release];
}

- (void)historyPressed
{
	PurposeHistoryViewController*	purposeHistoryView = [[PurposeHistoryViewController alloc] initWithRootViewController:_rootViewController withStyle:UITableViewStylePlain andFileName:@"nineDayPurposeHistory.inf"];
	
	purposeHistoryView.delegate = self;
	[self.navigationController pushViewController:purposeHistoryView animated:YES];
	[purposeHistoryView release];
}

- (void)scrollPurposeView
{
	CGPoint point = _purposeScrollView.contentOffset;

	_purposeScrollViewPosition = _purposeScrollViewPosition + 1;
	
	if( _purposeScrollViewPosition >= _purposeScrollViewLimitX )
	{
		_purposeScrollViewPosition = 0;
	}
	
	point.x = _purposeScrollViewPosition;
	_purposeScrollView.contentOffset = point;
		
	[self performSelector:@selector(scrollPurposeView) withObject:nil afterDelay:0.1f];
}

- (void)initSubView:(NSString*)purpose
{
	UIFont*	defaultFont = [UIFont fontWithName:@"NanumGothic" size:PRAY_DEFAULT_FONT_SIZE];
	
	if( _backgroundView == nil )
		_backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PRAYVIEW_IMG_BACKGROUND_DEFAULT]];

	[self.view addSubview:_backgroundView];
	
	if( _prayView == nil )
	{
		_prayView		= [[UITextView alloc] initWithFrame:CGRectMake(20, 60, 200, 255)];
	}
	
	_prayView.font = defaultFont;
	_prayView.backgroundColor = [UIColor clearColor];
	_prayView.textColor = [UIColor colorWithRed:GetRedf(PRAY_DEFAULT_FONT_COLOR)
										  green:GetGreenf(PRAY_DEFAULT_FONT_COLOR)
										   blue:GetBluef(PRAY_DEFAULT_FONT_COLOR) 
										  alpha:GetAlphaf(PRAY_DEFAULT_FONT_COLOR)];
	_prayView.editable = NO;
	_prayView.text = @"전능하신 천주 성부. \n천지의 창조주를 저는 믿나이다. 그 외아들 우리 주 예수 그리스도님 성령으로 인하여 동정 마리아께 잉태되어 나시고 본시오 빌라도 통치 아래에서 고난을 받으시며 십자가에 못박혀 돌아가시고 묻히셨으며 저승에 가시어 사흗날에 죽은 이들 가운데에서 부활하시고 하늘에 올라 전능하신 천주 성부 오른편에 앉으시며 그리로부터 산 이와 죽은 이를 심판하러 오시리라 믿나이다.\n성령을 믿으며 거룩하고 보편된 교회와 모든 성인의 통공을 믿으며 죄의 용서와 육신의 부활을 믿으며 영원한 삶을 믿나이다. 아멘.";
	[self.view addSubview:_prayView];
	
	[self updatePurposeView];
		 
	if(_rosaryView == nil )
	{
		_rosaryView = [[RosaryViewController alloc] init];
		_rosaryView.frame = CGRectMake(232, 50, 80, 280);
		_rosaryView.rosaryDelegate = self;
		[_rosaryView resetPosition];
	}
	[self.view addSubview:_rosaryView];
	
	if( _pointerView == nil )
		_pointerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:ROSARYVIEW_IMG_POINTER]];
	[self.view addSubview:_pointerView];
	
	_mysteryView = [[ImageButton alloc] initWithFrame:CGRectMake(0, 0, 320, 480) 
					   andShowThisImageForNormalState:nil 
						  thenShowThisWhenHighlighted:nil 
												  let:self 
										handleEventAt:@selector(mysteryViewPressed)];
	_mysteryView.hidden = YES;
	[self.rootViewController.view addSubview:_mysteryView];
}

- (void)showMystery:(NSInteger)rosaryIndex
{
	NSInteger index = 1;
	switch (rosaryIndex) {
		case ROSARYVIEW_INDEX_MYSTERY_FIRST: // 1단
			index = 1;
			break;
		case ROSARYVIEW_INDEX_MYSTERY_SECOND: // 2단
			index = 2;
			break;
		case ROSARYVIEW_INDEX_MYSTERY_THIRD: // 3단
			index = 3;
			break;
		case ROSARYVIEW_INDEX_MYSTERY_FOURTH: // 4단
			index = 4;
			break;
		case ROSARYVIEW_INDEX_MYSTERY_FIFTH: // 5단
			index = 5;
			break;
		default:
			return;
	}

	MysteryView* mysteryView = [MysteryView getMysteryViewForMystery:1 withIndex:index rootViewController:_rootViewController];
	[self.rootViewController.view addSubview:mysteryView];
	
	mysteryView.alpha = 0.0f;
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	mysteryView.alpha = 1.0f;
	[UIView commitAnimations];
}

- (void)hideMystery
{
	_mysteryView.hidden = NO;
	_mysteryView.alpha = 1.0f;
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(onMysteryHideComplete)];
	_mysteryView.alpha = 0.0f;
	[UIView commitAnimations];
}

- (void)onMysteryHideComplete
{
	_mysteryView.hidden = YES;
	
	[CaulyViewController hideBannerAD:NO];
}

- (void)mysteryViewPressed
{
	[self hideMystery];
}

- (void)updatePurposeView
{
	UIFont*	defaultFont = [UIFont fontWithName:@"NanumGothic" size:PRAY_DEFAULT_FONT_SIZE];

	if( _purposeLabel != nil )
	{
		[_purposeLabel removeFromSuperview];
		[_purposeLabel release];
	}
	
	if( _purposeScrollView != nil )
	{
		[_purposeScrollView removeFromSuperview];
		[_purposeScrollView release];
	}
	
	if( [_purpose sizeWithFont:defaultFont].width < 260 )
	{
		_purposeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 30)];
		_purposeLabel.textAlignment = UITextAlignmentCenter;
		_purposeLabel.text = _purpose;
		_purposeLabel.font = defaultFont;
		_purposeLabel.numberOfLines = 1;
		_purposeLabel.backgroundColor = [UIColor clearColor];
		_purposeLabel.textColor = [UIColor colorWithRed:GetRedf(PRAY_DEFAULT_FONT_COLOR)
												 green:GetGreenf(PRAY_DEFAULT_FONT_COLOR)
												  blue:GetBluef(PRAY_DEFAULT_FONT_COLOR) 
												 alpha:GetAlphaf(PRAY_DEFAULT_FONT_COLOR)];
		[self.view addSubview:_purposeLabel];
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(scrollPurposeView) object:nil];
	}
	else
	{
		NSString*	modifiedPurpose = [NSString stringWithFormat:@"%@ %@", _purpose, _purpose];
		_purposeLabel 		= [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [modifiedPurpose sizeWithFont:defaultFont].width, 30)];
		_purposeScrollView 	= [[UIScrollView alloc] initWithFrame:CGRectMake(10, 6, 300, 30)];
		
		_purposeLabel.text = modifiedPurpose;
		_purposeLabel.font = defaultFont;
		_purposeLabel.numberOfLines = 1;
		_purposeLabel.backgroundColor = [UIColor clearColor];
		_purposeLabel.textColor = [UIColor colorWithRed:GetRedf(PRAY_DEFAULT_FONT_COLOR)
												  green:GetGreenf(PRAY_DEFAULT_FONT_COLOR)
												   blue:GetBluef(PRAY_DEFAULT_FONT_COLOR) 
												  alpha:GetAlphaf(PRAY_DEFAULT_FONT_COLOR)];
		
		_purposeScrollView.backgroundColor = [UIColor clearColor];
		_purposeScrollView.showsVerticalScrollIndicator = NO;
		_purposeScrollView.userInteractionEnabled = NO;
		[_purposeScrollView setContentSize:_purposeLabel.frame.size];
		[_purposeScrollView addSubview:_purposeLabel];
		
		modifiedPurpose = [NSString stringWithFormat:@"%@ ", _purpose];
		_purposeScrollViewPosition = 0;
		_purposeScrollViewLimitX = [modifiedPurpose sizeWithFont:defaultFont].width;
		
		[self.view addSubview:_purposeScrollView];
		[self performSelector:@selector(scrollPurposeView) withObject:nil afterDelay:0.1f];
	}

}

@end

@implementation NineDayViewController

- (id)initWithRootViewController:(PrayViewController*)rootViewController
{
	if( (self = [super init]) != nil )
	{
		// 날짜에 따른 신비 초기화 부분 들어가야됨
		// _mysteryImageButtons = ...
		
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		PurposeDataList*	purposeList;
		
		if( NO == [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, @"nineDayPurposeHistory.inf"]] )
		{
			_purpose = @"세계 평화를 위하여 기도합니다.";
		}
		else
		{
			purposeList = [(PurposeDataList*)[NSKeyedUnarchiver unarchiveObjectWithFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, @"nineDayPurposeHistory.inf"]] retain];
			_purpose = [purposeList getPurposeWithIndex:[purposeList getNumberOfData] - 1].purpose;
		}

		_rootViewController = rootViewController;
	}
	
	return self;
}

- (void)viewDidLoad
{
	self.view.frame = CGRectMake(0, 0, 320, 390);
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:PRAYVIEW_IMG_BACKGROUND_DEFAULT]];
	self.title = @"9일기도";

	[self initSubView:_purpose];
	[self onSettingChanged:[PraySettingData getSettingDataFromDefaultPath]];
}

- (void)onSavePurpose:(NSString*)newPurpose;
{
	_purpose = newPurpose;
	
	[self updatePurposeView];
}

- (void)rosaryMoving
{
	_pointerView.hidden = YES;
}

- (void)rosaryEnd
{
	PraySettingData* data = [PraySettingData getSettingDataFromDefaultPath];
	data.curDay = data.curDay + 1;
	
	if( (data.enableLightMystery && data.curDay == 57) || (!data.enableLightMystery && data.curDay == 55) )
	{
		data.curDay = 0;
	}
	
	[PraySettingData saveSettingDataToDefaultPath:data];
	[self onSettingChanged:data];
}

- (void)positionChanged:(NSInteger)position withValue:(NSInteger)value
{
	_pointerView.hidden = NO;
	
	if( _vibrateOn )
		AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
	
	switch (value) {
		case ROSARYVIEW_INDEX_BALL:  	// 성모송 
			_prayView.text = @"은총이 가득하신 마리아님 기뻐하소서 주님께서 함께 계시니 여인중에 복되시며 태중의 아들 예수님 또한 복되시나이다. 천주의 성모 마리아님 이제와 저희 죽을 때에 저희 죄인을 위하여 빌어주소서. 아멘.";
			break;
		case 1:  	// never be called for this value
			break;
		case ROSARYVIEW_INDEX_CHAINTOBIGBALL:		// 영광송 구원송
		case ROSARYVIEW_INDEX_MEDAL:		// 기적의패
			_prayView.text = @"영광이 성부와 성자와 성령께 처음과 같이 이제와 항상 영원히 아멘. 예수님 저희 죄를 용서하시고 저희를 지옥불에서 구하시고 연옥 영혼을 돌보시며 가장 버림받은 영혼을 돌보소서. 아멘.";
			break;
		case ROSARYVIEW_INDEX_CROSS:		// 십자가 사도신경
			_prayView.text = @"전능하신 천주 성부.\n천지의 창조주를 저는 믿나이다. 그 외아들 우리 주 예수 그리스도님 성령으로 인하여 동정 마리아께 잉태되어 나시고 본시오 빌라도 통치 아래에서 고난을 받으시며 십자가에 못박혀 돌아가시고 묻히셨으며 저승에 가시어 사흗날에 죽은 이들 가운데에서 부활하시고 하늘에 올라 전능하신 천주 성부 오른편에 앉으시며 그리로부터 산 이와 죽은 이를 심판하러 오시리라 믿나이다.\n성령을 믿으며 거룩하고 보편된 교회와 모든 성인의 통공을 믿으며 죄의 용서와 육신의 부활을 믿으며 영원한 삶을 믿나이다. 아멘.";
			break;
		case ROSARYVIEW_INDEX_BIGBALL:		// 신비, 주의기도 
			[self showMystery:position];
			_prayView.text = @"하늘에 계신 우리 아버지 아버지의 이름이 거룩히 빛나시며 아버지의 나라가 오시며 아버지의 뜻이 하늘에서와 같이 땅에서도 이루어지소서. 오늘 저희에게 일용할 양식을 주시고 저희에게 잘못한 이를 저희가 용서하오니 저희 죄를 용서하시고 저희를 유혹에 빠지지 않게 하시고 악에서 구하소서. 아멘.";
			break;
		case ROSARYVIEW_INDEX_CHAINTOSTART:
			_prayView.text = @"영광이 성부와 성자와 성령께 처음과 같이 이제와 항상 영원히 아멘.";
			break;
		default:
			break;
	}
}

- (void)onSettingChanged:(PraySettingData *)data
{
	CGRect rect;
	
	if(_rosaryView == nil )
	{
		_rosaryView = [[RosaryViewController alloc] init];
		_rosaryView.frame = CGRectMake(PRAY_ROSARYVIEW_RIGHTHAND_LEFT, PRAY_ROSARYVIEW_TOP, PRAY_ROSARYVIEW_WIDTH, PRAY_ROSARYVIEW_HEIGHT);
		_rosaryView.rosaryDelegate = self;
		[_rosaryView resetPosition];
	}
	
	if( _prayView == nil )
	{
		_prayView		= [[UITextView alloc] initWithFrame:CGRectMake(PRAY_PRAYVIEW_RIGHTHAND_LEFT, PRAY_PRAYVIEW_TOP, PRAY_PRAYVIEW_WIDTH, PRAY_PRAYVIEW_HEIGHT)];
	}

	if( _backgroundView == nil )
	{
		_backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PRAYVIEW_IMG_BACKGROUND_DEFAULT]];
	}
	
	if( data.isLeftHanded )
	{
		rect = _prayView.frame;
		rect.origin.x = PRAY_PRAYVIEW_LEFTHAND_LEFT;
		_prayView.frame = rect;
		
		rect = _rosaryView.frame;
		rect.origin.x = PRAY_ROSARYVIEW_LEFTHAND_LEFT;
		_rosaryView.frame = rect;
		
		UIImage* backgroundImg = [UIImage imageNamed:PRAYVIEW_IMG_BACKGROUND_DEFAULT];
		_backgroundView.image = [UIImage imageWithCGImage:backgroundImg.CGImage scale:1.0f orientation:UIImageOrientationUpMirrored];
	}
	else 
	{
		rect = _prayView.frame;
		rect.origin.x = PRAY_PRAYVIEW_RIGHTHAND_LEFT;
		_prayView.frame = rect;
		
		rect = _rosaryView.frame;
		rect.origin.x = PRAY_ROSARYVIEW_RIGHTHAND_LEFT;
		_rosaryView.frame = rect;
		
		_backgroundView.image = [UIImage imageNamed:PRAYVIEW_IMG_BACKGROUND_DEFAULT];
	}
	
	if( data.enableLightMystery )
	{
		switch (data.curDay % 4) {
			case 1:
				_mysteryName = @"mystery_h";
				break;
			case 2:
				_mysteryName = @"mystery_b";
				break;
			case 3:
				_mysteryName = @"mystery_g";
				break;
			case 0:
				_mysteryName = @"mystery_y";
				break;
		}
	}
	else
	{
		switch (data.curDay % 3) {
			case 1:
				_mysteryName = @"mystery_h";
				break;
			case 2:
				_mysteryName = @"mystery_g";
				break;
			case 0:
				_mysteryName = @"mystery_y";
				break;
		}
	}
	
	[_rosaryView changeRosary:data.rosaryNum];
	
	if( _pointerView == nil )
		_pointerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:ROSARYVIEW_IMG_POINTER]];
	
	if( data.isLeftHanded )
	{
		CGPoint pointerViewCenter = _pointerView.center;
		pointerViewCenter.x = PRAY_POINTERVIEW_LEFTHAND_LEFT;
		pointerViewCenter.y = PRAY_POINTERVIEW_TOP;
		_pointerView.center = pointerViewCenter;
	}
	else
	{
		CGPoint pointerViewCenter = _pointerView.center;
		pointerViewCenter.x = PRAY_POINTERVIEW_RIGHTHAND_LEFT;
		pointerViewCenter.y = PRAY_POINTERVIEW_TOP;
		_pointerView.center = pointerViewCenter;
	}
}

// hide context menu for UITextField. What is this??
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
	UIMenuController*	menuController = [UIMenuController sharedMenuController];
	
	if (nil != menuController)
	{
		[UIMenuController sharedMenuController].menuVisible	= NO;
	}
	
	return NO;
}

@end